# -*- encoding: utf-8 -*-
import struct
import string

word_class = [u"惯用语", u"名词", u"代名词", u"形容词",
              u"副词", u"助动词", u"动词", u"及物动词",
              u"不及物动词", u"介系词", u"连接词", u"感叹词",
              u"名词", u"名词", u"字尾", u"字首"]
assert len(word_class) == 16

def get_len(str):    
    if ord(str[1]) == 255:
        l = 255 + ord(str[2])
        return 3, l
    else:
        l = ord(str[1])
        return 2, l

def convert(str):
    if not str: return ""
    off, l = get_len(str)
    t = ord(str[0])
    if 0x10 <= t < 0x20:
        return ""
    elif 0x20 <= t < 0x30:
        return convert(str[off+l:])
    elif t == 0x50:
        return u"<<同义字>>\n" + convert(str[1:])
    elif 0x60 <= t < 0x70:
        return "<<%s>>\n" % word_class[t-0x60] + convert(str[1:])

    s = (''.join([chr(ord(str[i]) ^ 0xa5) for i in range(off, off+l)]) + '\n')
    s = s.decode('big5hkscs', 'replace')
    return s + convert(str[off+l:])

def foo(s):
    t = s[0]

    if ord(s[1]) == 255:
        l = 255 + ord(s[2])
        s = s[3:]
    else:
        l = ord(s[1])
        s = s[2:]

    tres = []
    res = ''
    for i in range(l):
        raw = ord(s[i]) ^ 0xa5
        if raw >= 225:
            res += chr(raw - 225 + ord('a'))
        elif raw >= 193:
            res += chr(raw - 193 + ord('A'))
        elif raw == 172:
            tres.append(res)
            res = ''
        elif raw == 160:
            res += ' '
        elif raw == 168:
            res += '('
        elif raw >= 129:
            res += chr(raw - 129 + ord('a'))
        else:
            res += chr(raw)
    if res:
        tres.append(res)
    return (tres, t, s[l:])

def main2(ifname1, ifname2):
    data = []

    ifile = file(ifname1)
    while 1:
        s = ifile.read(4)
        if len(s) != 4:
            break
        data.append([struct.unpack('<I', s)[0] & 0x1FFFFF,
                     None])
    ifile.close()

    for i in range(len(data)-1):
        data[i][1] = data[i+1][0] - data[i][0] + 10

    ifile = file(ifname2)
    for i in range(len(data)):
        ifile.seek(data[i][0])
        if data[i][1] is not None:
            yield ifile.read(data[i][1])
        else:
            yield ifile.read()

def process(s, ofile):
    keys, t, des = foo(s)
    d2 = convert(des).encode('utf8')
    for key in keys:
        ofile.write('%%h %s\n' % key.decode('iso8859-1', 'replace').encode('utf8'))
        ofile.write('%%d\n%s\n' % d2)

def main3(ifname1, ifname2):
    import sys
    for s in main2(ifname1, ifname2):
        process(s, sys.stdout)

def main():
    for i in string.lowercase:
        ifname1 = 'etdic/%s.i50' % i
        ifname2 = 'etdic/%s.d50' % i
        main3(ifname1, ifname2)

if __name__ == '__main__':
    main()
